﻿using CKS.Core.Framework;
using CKS.PLC.Core.Event;
using Infrastructure;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;
using static FreeSql.Internal.GlobalFilter;

namespace CKS.PLC.Core.Alarm
{
    /// <summary>
    /// 氦检报警操作类
    /// </summary>
    public class OP150_HC_Alarm_Action
    {
        internal void Process(int bitId, bool bitErr,bool? bitOldValue)
        {
            try
            {
                var fsql = InternalApp.Fsql;
                //查出报警字典ID，
                var dict = fsql.Select<CksAlarmDict>().Where(x => x.PlcId == 15 && x.BitId == bitId).First();
                if (dict == null)
                    return;
                if (bitErr)
                {
                    //报警了新增报警记录
                    EventBus.AddLog($"氦检机{dict.SignalAddress}报警:{dict.FaultCase}");
                    //查询数据库，不存在则新增
                    var records = fsql.Select<CksAlarmRecord>()
                        .Where(a => a.Status == 1 && a.AlarmDictId == dict.Id)
                        .ToList();
                    if (records.Count == 0)
                    {
                        var record = new CksAlarmRecord()
                        {
                            AlarmDictId = dict.Id.ToInt(),
                            PlcId = 15,
                            StationCode = "OP150",
                            StartTime = DateTime.Now,
                            SignalAddress = dict.SignalAddress,
                            FaultCase = dict.FaultCase,
                            Solution = dict.Solution,
                            DeviceName = dict.DeviceName,
                            Status = 1,
                            AlarmCode = dict.AlarmCode,
                        };
                        fsql.Insert(record).ExecuteAffrows();
                    }
                }
                else
                {
                    //警报消除 

                    fsql.Update<CksAlarmRecord>().Set(a => a.Status, 10)
                        .Set(a => a.EndTime, DateTime.Now)
                        .Where(a => a.Status == 1 && a.AlarmDictId == dict.Id)
                        .ExecuteAffrows();
                    if (bitOldValue != null)
                    {
                        EventBus.AddLog($"氦检机设备报警消除:{dict.SignalAddress} ");
                        Debug.WriteLine($"{dict.SignalAddress}消除");
                    }
                }


            }
            catch (Exception ex)
            {

            }
        }
    }
}
